package com.outfood.service.impl;

import com.outfood.service.IStoreService;
import com.ruoyi.common.exception.BusinessException;
import lombok.extern.log4j.Log4j2;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfoodcat-master
 * @Package com.outfood.service.impl
 * @Date 2024-05-27 9:17
 * @Version 1.0
 */
@Log4j2
public class SleniumElemeOprationService {

    public WebDriver webDriver;

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver","C:\\drive\\chromedriver.exe");
        SleniumElemeOprationService sleniumElemeOprationService = new SleniumElemeOprationService();
        sleniumElemeOprationService.createWebDriver();
        sleniumElemeOprationService.elemePassword("ele5833tVUc","wm123456");

    }

    public WebDriver createWebDriver(){

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-cache");
        chromeOptions.addArguments("--disable-application-cache");
        chromeOptions.addArguments("--ignore-certificate-errors");
        chromeOptions.addArguments("--disable-extensions");
        chromeOptions.addArguments("--disable-software-rasterizer");
        chromeOptions.addArguments("--disable-images");
        chromeOptions.addArguments("--allow-running-insecure-content");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.setExperimentalOption("useAutomationExtension",false);
        chromeOptions.setExperimentalOption("excludeSwitches",new String[]{"enable-automation"});
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        this.webDriver = driver;
        return driver;
    }
    public Boolean elemeIspasswordLoingSuccess() {
        // 自定义一个等待条件，等待元素变得不可见
        ExpectedCondition<Boolean> invisibilityOfElement = new ExpectedCondition<Boolean>() {
            @NullableDecl
            @Override
            public Boolean apply(@NullableDecl WebDriver webDriver) {
                try {
                    boolean result = webDriver.getCurrentUrl().equals("https://melody.shop.ele.me/login");
                    if(result){
                        log.info("还是登录页面,继续等待");
                        return false;
                    }else{
                        return true;
                    }
                } catch (Exception e) {
                    log.error(e);
                    throw new RuntimeException(e);
                }
            }
        };
        Boolean result = null;
        try {
            result = new WebDriverWait(this.webDriver, 3).until(invisibilityOfElement);
            if(!result){
                log.info("元素最终没有消失说明登录没有成功");
            }
            log.info("最终返回结果为如下");
            log.info("最终返回结果为如下{}",webDriver.getCurrentUrl());
            return result;
        } catch (TimeoutException e) {
            log.error(e);
            return false;
        } catch (Exception e){
            log.error(e);
        }
        return false;

    }

    public void closevpnRemind(WebDriver webDriver){
        try {
            WebElement until = new WebDriverWait(this.webDriver, 2).until(
                    ExpectedConditions.visibilityOfElementLocated(By.className("baxia-dialog-close"))
            );
            until.click();
        } catch (Exception e) {
            log.info("没有出现vpn提示");
        }

    }

    public void shzk(WebDriver webDriver){
        ///html/body/div[2]/div/div[2]/div/div[2]/div[3]/button[1]
        try {

            WebElement until = new WebDriverWait(this.webDriver, 2).until(
                    ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[2]/div/div[2]/div/div[2]/div[3]/button[1]/span"))
            );
            until.click();
        } catch (Exception e) {
            log.info("没有出现稍后再看提示");
        }
    }

    //点击待出餐
    public void dcc(WebDriver webDriver){
        //*[@id="rc-tabs-0-tab-meal"]
        try {
            WebElement until = new WebDriverWait(this.webDriver, 2).until(
                    ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"rc-tabs-0-tab-meal\"]/span/span"))
            );
            until.click();
        } catch (Exception e) {
            log.info("没有出现待出餐按钮");
        }

    }

    public void elemePassword(String username, String password){

        try {
            this.webDriver.get("https://melody.shop.ele.me/login");
            //点击我已阅读条款
            this.webDriver.findElement(By.xpath("//*[@id='username_login']/div[3]/div/div/div/div/div[1]/label/span[1]/input")).click();
            //输入账号
            this.webDriver.findElement(By.xpath("//*[@id='username_login_username']")).sendKeys(username);
            //输入密码
            this.webDriver.findElement(By.xpath("//*[@id='username_login_password']")).sendKeys(password);
            //点击登录
            this.webDriver.findElement(By.xpath("//*[@id='username_login']/div[3]/div/div/div/button")).click();
            if(elemeIspasswordLoingSuccess()){
                log.info("登录成功");
                new WebDriverWait(webDriver, 3).until((WebDriver driver) -> {
                    JavascriptExecutor js = (JavascriptExecutor) driver;
                    Boolean result = (Boolean) js.executeScript("return document.readyState === 'complete'");
                    System.out.println("页面是否已经加载完成"+result);
                    return result;
                });
                log.info("开始获取strage信息");
                //获取cookie
                JavascriptExecutor js = (JavascriptExecutor) webDriver;
                String ksid = (String) js.executeScript("return window.localStorage.getItem('ksid')");
                String shopId = (String) js.executeScript("return window.localStorage.getItem('shopId')");
                String shopName = (String) js.executeScript("return window.localStorage.getItem('shopName')");
                log.info("{}{}{}",ksid,shopId,shopName);

                this.webDriver.get("https://melody.shop.ele.me/app/shop/"+shopId+"/order__processing#app.shop.order.processing");
                closevpnRemind(this.webDriver); //关闭vpn提示
                webDriver.switchTo().frame("app_shop_order_processing");
                shzk(webDriver);
                dcc(webDriver);
                try {
                    Thread.sleep(2000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                WebElement element = webDriver.findElement(By.className("ant-spin-container"));
                List<WebElement> elements = element.findElements(By.xpath("./div"));
                for (WebElement webElement : elements) {
                    try {
                        System.out.println(webElement.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

//                elements.forEach(a ->{
//                    System.out.println(a.getText());
//                });
                //                try {
//                    webDriver.quit();
//                } catch (Exception e) {
//                    log.error(e);
//                }
            }else{

            }
        } catch (Exception e) {
            this.webDriver.close();
            this.webDriver.quit();
            throw e;
        }


    }
}
